
import config from '../config'
import jwt from 'jsonwebtoken'

const format = (val) => {
  const valTemp = Number(val)
  return (valTemp < 10 ? `0${valTemp}` : valTemp)
}

const utils = {
  mathRandNum: (length) => {
    var Num = ''
    for (var i = 0; i < length; i++) {
      Num += Math.floor(Math.random() * 10)
    }
    return Num
  },
  ifPhoneNum: (phone) => {
    return new Promise((resolve, reject) => {
      const regex = /^1[345789]\d{9}$/
      if (regex.test(phone)) {
        resolve(true)
      } else {
        reject(new Error('无效的手机号'))
      }
    })
  },
  currentTime: () => {
    const date = new Date()
    const o = {
      yyyy: date.getFullYear(),
      m: format((date.getMonth() + 1)),
      dd: format(date.getDate()),
      hh: format(date.getHours()),
      mm: format(date.getMinutes()),
      ss: format(date.getSeconds()),
      S: date.getMilliseconds()
    }
    return (`${o.yyyy}-${o.m}-${o.dd} ${o.hh}:${o.mm}:${o.ss}.${o.S}`)
  },
  currentTimeStamp: () => {
    return new Date().getTime()
  },
  randomString: (len) => {
    len = len || 32
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = $chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  },
  decodeToken: (token) => {
    return new Promise((resolve, reject) => {
      const decoded = jwt.verify(token, config.passCode)
      if (token) {
        resolve({
          userName: decoded.userName
        })
      } else {
        reject(new Error('无效的Token'))
      }
    })
  }
}

export default utils
